import gpiod
import time

# Setup
chip = gpiod.Chip('gpiochip0')  # This accesses the first GPIO chip on the Pi
trig_line = chip.get_line(15)   # Replace with your trigger pin number
echo_line = chip.get_line(14)   # Replace with your echo pin number

# Configure the lines
trig_line.request(consumer="trig", type=gpiod.LINE_REQ_DIR_OUT)
echo_line.request(consumer="echo", type=gpiod.LINE_REQ_DIR_IN)

# Function to measure distance in cm
def get_distance():
    # Trigger the sensor
    trig_line.set_value(1)
    time.sleep(0.00001)  # 10 µs pulse
    trig_line.set_value(0)

    # Wait for the echo response
    start_time = time.time()
    while echo_line.get_value() == 0:
        start_time = time.time()

    while echo_line.get_value() == 1:
        stop_time = time.time()

    # Calculate distance in cm
    time_elapsed = stop_time - start_time
    distance_cm = (time_elapsed * 34300) / 2  # Sound speed is 34300 cm/s
    return distance_cm

# Main loop to print the distance in feet and inches
while True:
    distance_cm = get_distance()
    print(f"Distance: {distance_cm:.2f} cm")
    time.sleep(1)
